package com.starinside.wp.controller.api;

import com.alibaba.fastjson.JSONArray;
import com.starinside.wp.components.MemVerificationCache;
import com.starinside.wp.domain.course.CourseAppendix;
import com.starinside.wp.domain.course.CourseTool;
import com.starinside.wp.domain.course.VendorCourse;
import com.starinside.wp.domain.course.VendorCourseContent;
import com.starinside.wp.domain.course.po.CourseContentV2PO;
import com.starinside.wp.domain.course.po.CourseToolPO;
import com.starinside.wp.domain.course.po.CourseV2ListPO;
import com.starinside.wp.domain.course.po.SysDictDataPO;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.repository.CourseToolRepository;
import com.starinside.wp.repository.VendorCourseContentRepository;
import com.starinside.wp.service.VendorCourseService;
import com.starinside.wp.utils.Convert;
import com.starinside.wp.utils.RemoteCallUtil;
import com.tuo51.foudation.utils.CopyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


@RestController
@RequestMapping("/wx/api/vendor_courseV2")
@Slf4j
@Api(tags = "教学 - 课程管理")
public class APIVendorCourseV2Controller {

    @Autowired
    private VendorCourseService courseService;

    @Autowired
    protected MemVerificationCache cache;


    @Autowired
    private VendorCourseContentRepository courseContentRepository;

    @Value("${server.edit.url}")
    private String editServerURL;

    @Autowired
    private CourseToolRepository courseToolRepository;



    @ApiOperation(value = "课程 - 详情")
    @PostMapping("/getCourseDetails")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "courseId", value = "课程id", required = true, dataType = "string"),
    })
    public StatusResponse getCourseDetails( String courseId) {
        VendorCourse vendorCourse = courseService.getVendorCourse(courseId);
        if (Objects.isNull(vendorCourse)){
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        CourseV2ListPO courseV2ListPO = new CourseV2ListPO();
        CopyUtils.copyProperties(vendorCourse,courseV2ListPO);
        List<Map> maps = JSONArray.parseArray(courseV2ListPO.getDetails(), Map.class);
        maps.stream().forEach(o->{
            if (StringUtils.equals(o.get("label").toString(),"月龄")){
                o.put("value",vendorCourse.getAgeLow()+"-"+vendorCourse.getAgeHigh());
            }
        });
        courseV2ListPO.setDetailsList(maps);

        List<VendorCourseContent>  list = courseService.findByCourseId(vendorCourse.getId(),0);
        List<CourseContentV2PO> listPO =  getCourseContentV2PO(list);

        //教保指引
        List<VendorCourseContent>  list1 = courseService.findByCourseId(vendorCourse.getId(),1);

        List<VendorCourseContent>  vendorCourseContentList = courseService.findVendorPackageId(courseId);
        list1.addAll(vendorCourseContentList);
        List<CourseContentV2PO> listPO1 =  getCourseContentV2PO(list1);

        Map map = new HashMap();
        map.put("vendorCourse",courseV2ListPO);
        map.put("courseContent",listPO);
        map.put("guideContent",listPO1);
        return StatusResponse.success(map);
    }

    public   List<CourseContentV2PO>  getCourseContentV2PO(  List<VendorCourseContent>  list ){
        List<CourseContentV2PO> listPO = new ArrayList<>();
        for (int i = 0; i <list.size() ; i++) {
            CourseContentV2PO po  = new CourseContentV2PO();
            CopyUtils.copyProperties(list.get(i),po);
            if (StringUtils.equals(list.get(i).getParentId(),"0")){
                CourseContentV2PO po1  = new CourseContentV2PO();
                CopyUtils.copyProperties(list.get(i),po1);
                //查询下级列表
                po.setContentList( getParentId(list.get(i).getId(),list));
                //教具集合
                List<CourseToolPO> toolPOList =  getToolPOList(list.get(i));
                po.setToolList(toolPOList);

                listPO.add(po);
            }
        }
        return  listPO;
    }
    List<CourseContentV2PO>  getParentId(String id,List<VendorCourseContent>  vendorCourseContentList){
        List<CourseContentV2PO> listPO = new ArrayList<>();
        List<VendorCourseContent>  list = getVendorCourseContentParentId(id,vendorCourseContentList);
        for (int j = 0; j < list.size(); j++) {
            CourseContentV2PO po1  = new CourseContentV2PO();
            CopyUtils.copyProperties(list.get(j),po1);
            //循环  id  不能为 自己
            if (!StringUtils.equals(id,po1.getId())){
                po1.setContentList(getParentId(po1.getId(),vendorCourseContentList));
            }
            //教具集合
            List<CourseToolPO> toolPOList =  getToolPOList(list.get(j));
            po1.setToolList(toolPOList);
            listPO.add(po1);
        }
        return listPO;
    }

    List<VendorCourseContent>  getVendorCourseContentParentId(String id, List<VendorCourseContent>  vendorCourseContentList){
        List<VendorCourseContent> list = new ArrayList<>();
        for (int i = 0; i < vendorCourseContentList.size(); i++) {
            if (StringUtils.equals(id,vendorCourseContentList.get(i).getParentId())){
                list.add(vendorCourseContentList.get(i));
            }
        }
        return list;
    }



    List<CourseToolPO> getToolPOList(VendorCourseContent courseContent){
        List<CourseToolPO> toolPOList = new ArrayList<>();
        if (Objects.nonNull(courseContent.getTools())){
            List<CourseTool>  list1  = courseToolRepository.findByIdIn(Convert.toStrArray(courseContent.getTools()));
            for (int k = 0; k < list1.size(); k++) {
                CourseToolPO courseToolPO = new CourseToolPO();
                CopyUtils.copyProperties(list1.get(k),courseToolPO);
                String id  = list1.get(k).getId();
                List<CourseTool>  list3  = courseToolRepository.findByParentId(id);
                List<CourseToolPO> toolPOList1 = new ArrayList<>();
                for (int l = 0; l < list3.size(); l++) {
                    CourseToolPO courseToolPO1 = new CourseToolPO();
                    CopyUtils.copyProperties(list3.get(l),courseToolPO1);
                    toolPOList1.add(courseToolPO1);
                }
                courseToolPO.setList(toolPOList1);
                toolPOList.add(courseToolPO);
            }
        }
        return toolPOList;
    }

    @ApiOperation(value = "小群体课 - 附件")
    @PostMapping("/courseAppendix")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
    })
    public StatusResponse courseAppendix() {
        List<CourseAppendix> list = courseService.courseAppendix();
        return StatusResponse.success(list);
    }


    @ApiOperation(value = "课程V2 - 列表")
    @PostMapping("/courseListV2")
    public StatusResponse courseListV2( String title, String age, String week, String face, Integer type, PagerQuery pagerQuery) {

        Page<VendorCourse> vendorCourses = courseService.courseListV2(title, age, week, face,type,pagerQuery);
        List<CourseV2ListPO> listPOS = new ArrayList<>();
        for (int i = 0; i < vendorCourses.getContent().size() ; i++) {
            CourseV2ListPO courseV2ListPO = new CourseV2ListPO();
            CopyUtils.copyProperties(vendorCourses.getContent().get(i),courseV2ListPO);
            List<Map> maps = JSONArray.parseArray(vendorCourses.getContent().get(i).getDetails(), Map.class);
            if (Objects.nonNull(maps)){
                for (int j = 0; j < maps.size(); j++) {
                    if (StringUtils.equals(maps.get(j).get("label").toString(),"周次")){
                        courseV2ListPO.setWeek(maps.get(j).get("value").toString());
                    }
                    if (StringUtils.equals(maps.get(j).get("label").toString(),"教材")){
                        courseV2ListPO.setTextbook(maps.get(j).get("value").toString());
                    }
                    if (StringUtils.equals(maps.get(j).get("label").toString(),"面向")){
                        courseV2ListPO.setFace(maps.get(j).get("value").toString());
                    }
                }
            }

            courseV2ListPO.setDetailsList(maps);
            listPOS.add(courseV2ListPO);
        }
        return StatusResponse.success(new PageImpl<>(listPOS, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), vendorCourses.getTotalElements()));
    }


    @ApiOperation(value = "课程V2 - 教保指引公共分类")
    @PostMapping("/categoryTypeByGuide")
    public StatusResponse categoryTypeByGuide(String courseId, Integer categoryType) {

        VendorCourse vendorCourse = courseService.getVendorCourse(courseId);
        if (Objects.isNull(vendorCourse)){
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        CourseV2ListPO courseV2ListPO = new CourseV2ListPO();
        CopyUtils.copyProperties(vendorCourse,courseV2ListPO);
        List<Map> maps = JSONArray.parseArray(courseV2ListPO.getDetails(), Map.class);
        maps.stream().forEach(o->{
            if (StringUtils.equals(o.get("label").toString(),"月龄")){
                o.put("value",vendorCourse.getAgeLow()+"-"+vendorCourse.getAgeHigh());
            }
        });
        courseV2ListPO.setDetailsList(maps);

        //教保指引
        List<VendorCourseContent>  list1 = courseService.findByCourseId(vendorCourse.getId(),1);

        List<VendorCourseContent>  vendorCourseContentList = courseService.findVendorPackageId(courseId);
        list1.addAll(vendorCourseContentList);
        List<CourseContentV2PO> listPO1 =  getCourseContentV2PO(list1);

        List<CourseContentV2PO> listPO2 = new ArrayList<>();
        for (int i = 0; i < listPO1.size(); i++) {
            if (listPO1.get(i).getCategoryType() == categoryType){
                listPO2.add(listPO1.get(i));
            }
        }
        return StatusResponse.success(listPO2);
    }


    @ApiOperation(value = "获取字典")
    @PostMapping("/getData")
    public StatusResponse getData( String dictType, Integer type) {
        Map p  = new HashMap();

        if (type == 1){
            if (StringUtils.equals("tc_face",dictType)){
                dictType = "tc_family_face";
            }
            if (StringUtils.equals("tc_week",dictType)){
                dictType = "tc_family_week";
            }
            if (StringUtils.equals("tc_month",dictType)){
                dictType = "tc_family_month";
            }
        }
        if (type == 2){

            if (StringUtils.equals("tc_week",dictType)){
                dictType = "tc_group_week";
            }
            if (StringUtils.equals("tc_month",dictType)){
                dictType = "tc_group_month";
            }
        }
        p.put("dictType",dictType);
        List<SysDictDataPO> list = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", p, null, SysDictDataPO.class, "调用edit推送消息出错");
        return StatusResponse.success(list);
    }

    @ApiOperation(value = "获取字典集合")
    @PostMapping("/getDatas")
    public StatusResponse getDatas( Integer type) {
        if (Objects.nonNull(type)){
            type = 0;
        }
        Map map = new HashMap();
        if (type == 0){
            Map p  = new HashMap();
            p.put("dictType","tc_face");
            List<SysDictDataPO> list = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", p, null, SysDictDataPO.class, "调用edit推送消息出错");
            map.put("tc_face",list);

            Map week  = new HashMap();
            week.put("dictType","tc_week");
            List<SysDictDataPO> weekList = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", week, null, SysDictDataPO.class, "调用edit推送消息出错");
            map.put("tc_week",weekList);

            Map month  = new HashMap();
            month.put("dictType","tc_month");
            List<SysDictDataPO> monthList = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", month, null, SysDictDataPO.class, "调用edit推送消息出错");
            map.put("tc_month",monthList);
        }

        if (type == 1){
            Map p  = new HashMap();
            p.put("dictType","tc_family_face");
            List<SysDictDataPO> list = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", p, null, SysDictDataPO.class, "调用edit推送消息出错");
            map.put("tc_face",list);

            Map week  = new HashMap();
            week.put("dictType","tc_family_week");
            List<SysDictDataPO> weekList = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", week, null, SysDictDataPO.class, "调用edit推送消息出错");
            map.put("tc_week",weekList);

            Map month  = new HashMap();
            month.put("dictType","tc_family_month");
            List<SysDictDataPO> monthList = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", month, null, SysDictDataPO.class, "调用edit推送消息出错");
            map.put("tc_month",monthList);
        }


        if (type == 2){
            Map week  = new HashMap();
            week.put("dictType","tc_group_week");
            List<SysDictDataPO> weekList = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", week, null, SysDictDataPO.class, "调用edit推送消息出错");
            map.put("tc_week",weekList);

            Map month  = new HashMap();
            month.put("dictType","tc_group_month");
            List<SysDictDataPO> monthList = RemoteCallUtil.callOfList(editServerURL + "/system/dict/data/list_v2", month, null, SysDictDataPO.class, "调用edit推送消息出错");
            map.put("tc_month",monthList);
        }

        return StatusResponse.success(map);
    }
}
